<template>
  <div class='add-article'>
    <p>新建文章</p>
    <el-form ref="form" :model="form" :rules="rules">
      <el-form-item prop="cover">
        <!-- 用来显示封面的图片 -->
        <img :src="form.cover" alt="" class="cover-img" ref="imgRef" v-if="form.cover" @click="choiceCover" />
        <img src="@/assets/cover.jpg" alt="" class="cover-img" v-else @click="choiceCover" />
        <br />
        <!-- 文件选择框，默认被隐藏 -->
        <input type="file" style="display: none;" accept="image/*" ref="iptFileRef" @change="onCoverChangeFn" />
        <!-- 选择封面的按钮 -->
        <el-button type="text" @click="choiceCover">+ 选择封面</el-button>
      </el-form-item>

      <el-form-item prop="columnId">
        <span style="font-size: 14px;color: #606266;line-height: 40px;">所属专栏</span><br>
        <el-select v-model="form.columnId" placeholder="请选择文章所属专栏" style="width: 50%">
          <el-option v-for="column in columnList" :key="column.id" :label="column.title" :value="column.id"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item prop="title">
        <span style="font-size: 14px;color: #606266;line-height: 40px;">文章标题</span><br>
        <el-input v-model="form.title" placeholder="请输入文章标题" style="width: 50%"></el-input>
      </el-form-item>

      <el-form-item prop="excerpt">
        <span style="font-size: 14px;color: #606266;line-height: 40px;">文章引言</span><br>
        <el-input type="textarea" v-model="form.excerpt" style="width: 50%" placeholder="请输入文章引言"></el-input>
      </el-form-item>

      <el-form-item prop="content">
        <span style="font-size: 14px;color: #606266;line-height: 40px;">文章详情</span>
        <div style="border: 1px solid #ccc">
          <!-- 工具栏 -->
          <Toolbar style="border-bottom: 1px solid #ccc" :editor="editor" :defaultConfig="toolbarConfig" />
          <!-- 编辑器 -->
          <Editor style="height: 400px; overflow-y: hidden" :defaultConfig="editorConfig" v-model="form.content"
            @onChange="onChange" @onCreated="onCreated" />
        </div>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="onSubmit" style="width: 160px">发表文章</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { getAllColumns } from '@/api/column'
import { addArticle } from '@/api/article'

export default {
  name: 'MyAddArticle',
  data () {
    return {
      form: {
        cover: '',
        columnId: '',
        title: '',
        excerpt: '',
        content: ''
      },
      columnList: [],
      editor: null,
      toolbarConfig: {
        // toolbarKeys: [ /* 显示哪些菜单，如何排序、分组 */ ],
        // excludeKeys: [ /* 隐藏哪些菜单 */ ],
      },
      editorConfig: {
        placeholder: '请输入内容...',
        // autoFocus: false,

        // 所有的菜单配置，都要在 MENU_CONF 属性下
        MENU_CONF: {}
      },
      rules: {
        cover: [
          { required: true, message: '请选择文章封面', trigger: ['blur', 'change'] }
        ],
        title: [
          { required: true, message: '请输入文章标题', trigger: 'blur' }
        ],
        columnId: [
          { required: true, message: '请选择文章所属专栏', trigger: 'change' }
        ],
        excerpt: [
          { required: true, message: '请输入文章引言', trigger: 'blur' }
        ],
        content: [
          { required: true, message: '请输入文章内容', trigger: 'blur' }
        ]
      }
    }
  },
  components: {
    Editor,
    Toolbar
  },
  methods: {
    choiceCover () {
      this.$refs.iptFileRef.click()
    },
    // 封面选择改变的事件
    onCoverChangeFn (e) {
      // 获取用户选择的文件列表
      const files = e.target.files
      if (files.length === 0) {
        // 用户没有选择封面
        this.form.cover = null
      } else {
        const fr = new FileReader()
        fr.readAsDataURL(files[0])
        fr.onload = (e) => {
          this.form.cover = e.target.result
        }
      }
    },
    onCreated (editor) {
      this.editor = Object.seal(editor) // 【注意】一定要用 Object.seal() 否则会报错
    },
    onChange (editor) {
      // onChange 时获取编辑器最新内容
      this.form.content = editor.getHtml()
    },
    getEditorText () {
      const editor = this.editor
      if (editor == null) return
      console.log(editor.getText()) // 执行 editor API
    },
    async getColumns () {
      const res = await getAllColumns()
      if (res.code === 0) {
        this.columnList = res.data
      }
    },
    onSubmit () {
      this.$refs.form.validate(async valid => {
        if (valid) {
          const res = await addArticle({ ...this.form, userId: this.$store.getters.userId })
          if (res.code === 0) {
            this.$message.success(res.msg)
            this.$router.push(`/column/${this.form.columnId}`)
          } else {
            this.$message.error(res.msg)
          }
        } else {
          return false
        }
      })
    }
  },
  created () {
    this.getColumns()
  },
  mounted () { },
  beforeDestroy () {
    const editor = this.editor
    if (editor == null) return
    editor.destroy() // 组件销毁时，及时销毁 editor ，重要！！！
  }
}
</script>

<style lang='less' scoped>
.add-article {
  width: 980px;
  margin: 0 auto;

  p {
    padding: 30px 0;
    font-size: 24px;
  }

  // 设置图片封面的宽高
  .cover-img {
    width: 50%;
    height: 200px;
    object-fit: cover;
  }

  :deep(.el-form-item__content) {
    margin-left: 0 !important;
  }
}

:deep(.el-form-item__label) {
  text-align: left !important;
}
</style>
<style src="@wangeditor/editor/dist/css/style.css">

</style>
